﻿using Microsoft.EntityFrameworkCore;
using Mysqlx.Crud;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Order;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.Order;
using ZH.Infrastructure.Dto.Response.Yuyue;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ZH.Service.Instance
{

    [Inject_]
    public class Order_Service : Base_Service, I_Order_Service
    {
        private readonly Order_IOC _order_IOC;
        private readonly Emp_IOC _emp_IOC;
        private readonly Room_IOC _room_IOC;
        private readonly Mobile_IOC _mobile_IOC;
        private readonly Yuyue_IOC _yuyue_IOC;

        public Order_Service(Yuyue_IOC yuyue_IOC,Order_IOC order_IOC,Emp_IOC emp_IOC,Room_IOC room_IOC,Mobile_IOC mobile_IOC)
        {
            _order_IOC= order_IOC;
            _emp_IOC = emp_IOC;
            _room_IOC = room_IOC;
            _mobile_IOC = mobile_IOC;
            _yuyue_IOC = yuyue_IOC;
        }

        public async Task<Api_Response_Dto> Cashier_Add_Order(Order_Cashier_Request_Dto dto)
        {

            var emp = await _emp_IOC._emp_EFCore.QueryAll(e => e.EmpId == dto.eid).FirstOrDefaultAsync();

            var room = await _room_IOC._room_EFCore.QueryAll(r => r.Roid == dto.rid).FirstOrDefaultAsync();

            Infrastructure.EFCore.MySql.Order order = new Infrastructure.EFCore.MySql.Order()
            {
                OrId = dto.oid!,
                OrCreatTime =  DateTime.Parse(dto.otime!),
                OrMid = dto.mid,
                OrMoney = decimal.Parse(dto.originalprice!),
                OrPayment = null,
                Emid = dto.eid,
                Roid = dto.rid,
                OrStatus = 2,
                DiscountPrice =  decimal.Parse(dto.discountedprice!)
            };

            _order_IOC._order_EFCore.Add(order);

            var one = await _order_IOC._order_EFCore.SaveChangesAsync();

            emp.WorkStatus = "忙碌";
            room.Rostart = "使用中";

            _emp_IOC._emp_EFCore.Update(emp);
            _room_IOC._room_EFCore.Update(room);

            await _emp_IOC._emp_EFCore.SaveChangesAsync();
            await _room_IOC._room_EFCore.SaveChangesAsync();

            if (one > 0) {
                List<Orderdetail> details = new List<Orderdetail>();

                foreach (var item in dto.productlist!)
                {
                    Orderdetail detail = new Orderdetail()
                    {
                        Odid = Config.GUID(),
                        OrId = dto.oid,
                        OdName = item.itemName,
                        OdDuration = item.duration,
                        OdMoney = item.price,
                        OdCreateTime = DateTime.Parse(dto.otime!)
                    };

                    details.Add(detail);
                }

                _order_IOC._orderdetail_EFCore.AddRange(details);

                var two = await _order_IOC._orderdetail_EFCore.SaveChangesAsync();

                var mobile = await _mobile_IOC._mobile_EFCore.QueryAll(m => m.Mid == dto.mid).FirstOrDefaultAsync();

                if (mobile!.MemberLevel == "新用户") {

                    mobile.MemberLevel = "普通会员";

                    _mobile_IOC._mobile_EFCore.Update(mobile);

                    await _mobile_IOC._mobile_EFCore.SaveChangesAsync();
                }

                if (two > 0)
                {
                    return Result(two, "成功生成订单");
                }
                else {
                    return Result(0, "无法生成订单");
                }
                
            }
            else
            {
                return Result(0, "无法生成订单");
            }

        }

        public async Task<Api_Response_Dto> Cashier_Order_Service_Completed(Service_Completed dto)
        {
            var count = 0;

            var order = await _order_IOC._order_EFCore.QueryAll(o => o.OrId == dto.oid).FirstOrDefaultAsync();
            var emp = await _emp_IOC._emp_EFCore.QueryAll(e => e.EmpId == dto.eid).FirstOrDefaultAsync();
            var appoint = await _yuyue_IOC._yuyue_EFCore.QueryAll(r => r.Aid == dto.oid).FirstOrDefaultAsync();


            if (appoint != null)
            {
                appoint.Status = "待支付";
                _yuyue_IOC._yuyue_EFCore.Update(appoint);
                await _yuyue_IOC._yuyue_EFCore.SaveChangesAsync();

            }

            order.OrStatus = 1;

            if (emp != null) {

                emp.WorkStatus = "空闲";
                _emp_IOC._emp_EFCore.Update(emp);
                count += await _emp_IOC._emp_EFCore.SaveChangesAsync();
            }

            _order_IOC._order_EFCore.Update(order);
            

            count += await _order_IOC._order_EFCore.SaveChangesAsync();
           

            return Result(count);
        }

        public async Task<Api_Response_Dto> Cashier_Order_Settlement(Order_Settlement dto)
        {
            var count = 0;

            var order = await _order_IOC._order_EFCore.QueryAll(o => o.OrId == dto.oid).FirstOrDefaultAsync();
            var room = await _room_IOC._room_EFCore.QueryAll(r => r.Roid == dto.rid).FirstOrDefaultAsync();
            var appoint = await _yuyue_IOC._yuyue_EFCore.QueryAll(r => r.Aid == dto.oid).FirstOrDefaultAsync();


            if (appoint != null) {
                appoint.Status = "已完成";
                _yuyue_IOC._yuyue_EFCore.Update(appoint);
                await _yuyue_IOC._yuyue_EFCore.SaveChangesAsync();

            }

            order.OrStatus = 3;
            order.OrPayment = dto.paymentMethod;
            room.Rostart = "空闲";

            _order_IOC._order_EFCore.Update(order);
            _room_IOC._room_EFCore.Update(room);

            count += await _order_IOC._order_EFCore.SaveChangesAsync();
            count += await _room_IOC._room_EFCore.SaveChangesAsync();

            return Result(count);
        }

        public async Task<Api_Response_Dto> Get_Cashier_Order()
        {
            var data = await _order_IOC._order_EFCore.QueryAll().ToListAsync();

            var detail = await _order_IOC._orderdetail_EFCore.QueryAll().ToListAsync();

            var mobile = await _mobile_IOC._mobile_EFCore.QueryAll().ToListAsync();

            var emp = await _emp_IOC._emp_EFCore.QueryAll().ToListAsync();

            var room = await _room_IOC._room_EFCore.QueryAll().ToListAsync();

            var order = from o in data
                              select new Order_Cashier_Response_Dto
                              {
                                  id = 0,
                                  orderNumber = o.OrId,
                                  createTime = o.OrCreatTime.ToString(),
                                  customerName = mobile.Where( m => m.Mid == o.OrMid ).FirstOrDefault() != null ? mobile.Where(m => m.Mid == o.OrMid).FirstOrDefault()!.Mname : "",
                                  customerPhone = mobile.Where(m => m.Mid == o.OrMid).FirstOrDefault() != null ? mobile.Where(m => m.Mid == o.OrMid).FirstOrDefault()!.Mphone : "",
                                  membershipLevel = mobile.Where(m => m.Mid == o.OrMid).FirstOrDefault() != null ? mobile.Where(m => m.Mid == o.OrMid).FirstOrDefault()!.MemberLevel : "",
                                  service = detail.Where( d => d.OrId == o.OrId ).FirstOrDefault() != null ? detail.Where(d => d.OrId == o.OrId).FirstOrDefault()!.OdName : "",
                                  duration = detail.Where(d => d.OrId == o.OrId).FirstOrDefault() != null ? detail.Where(d => d.OrId == o.OrId).FirstOrDefault()!.OdDuration+"分钟" : "",
                                  amount = o.OrMoney.ToString(),
                                  discount = o.DiscountPrice.ToString(),
                                  status = o.OrStatus,
                                  paymentMethodText = o.OrPayment,
                                  therapist = emp.Where( e => e.EmpId == o.Emid ).FirstOrDefault() != null ? emp.Where(e => e.EmpId == o.Emid).FirstOrDefault()!.Ename : "",
                                  roomName = room.Where(r => r.Roid == o.Roid).FirstOrDefault() != null ? room.Where(r => r.Roid == o.Roid).FirstOrDefault()!.Roname : "",
                                  notes = ""
                              };

            // 将查询结果转换为列表以便修改
            var list = order.ToList();

            // 为每个元素分配自增ID
            int currentId = 1;
            foreach (var item in list)
            {
                item.id = currentId++;
            }

            var count = list.Count();

            if (count > 0)
            {
                return Result(1, "ok", new { data = list, total = count });
            }
            else
            {
                return Result(0);
            }
        }

        public async Task<Api_Response_Dto> Get_Order(Order_Request_Dto Dto)
        {

            var data = await _order_IOC._order_EFCore.QueryAll(out int total,
                  Convert.ToInt32(Dto.page), Convert.ToInt32(Dto.limit),
                  true,
                  o => o.OrId
                  ).ToListAsync();

            return Result(1, "ok", new
            {
                total,
                data
            });

        }

        public async Task<Api_Response_Dto> Get_Order_Xq(string? id)
        {
            var data = await _order_IOC._orderdetail_EFCore.QueryAll(d => d.OrId == id).FirstAsync();

            return Result(1, "ok", new
            {
                data
            });

        }

        public async Task<Api_Response_Dto> Get_toOrder(Order_Request_Dto Dto)
        {
            // 获取当天的起始和结束时间
            var todayStart = DateTime.Today; // 今天00:00:00
            var todayEnd = DateTime.Today.AddDays(1).AddTicks(-1); // 今天23:59:59.9999999

            var data = await _order_IOC._order_EFCore.QueryAll(out int total,
                           Convert.ToInt32(Dto.page), Convert.ToInt32(Dto.limit),
                           true,
                           o => o.OrId,
                           // 添加日期筛选条件，只查询当天订单
                           d => d.OrCreatTime >= todayStart && d.OrCreatTime <= todayEnd
                           ).ToListAsync();

            return Result(1, "ok", new
            {
                total,
                data
            });
        }
    }
}
